<?php
/**
 *
 * @copyright  flx
 * @author Jiangtian
 */
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Asia/ShangHai');
header("Content-type: text/json; charset=utf-8");
require_once __DIR__."/common/DB.php";
//require_once __DIR__."/curls_get.php";

/** 读取excel表格获取用户id */
function getExcel($multi){//是否复合数组或仅id数组
    $i = 0;
    $uids = array();
    /** PHPExcel_IOFactory */
    require_once __DIR__.'/Classes/PHPExcel/IOFactory.php';

    // Check prerequisites
    if (!file_exists(__DIR__."/Excel/weibo.xlsx")) {
        exit("not found weibo.xlsx.\n");
    }
     
    $reader = PHPExcel_IOFactory::createReader('Excel2007'); //设置以Excel格式(Exce工作簿)
    $PHPExcel = $reader->load(__DIR__."/Excel/weibo.xlsx"); // 载入excel文件
    $sheetCount = $PHPExcel->getSheetCount();//获取工作表的数目
    $sheetNames = $PHPExcel->getSheetNames();

    for($i = 0; $i < $sheetCount; $i++){
        $j = 0;$dataset = array();
        $sheet = $PHPExcel->getSheet($i); // 读取第n个工作表
        $highestRow = $sheet->getHighestRow(); // 取得总行数

        /** 循环读取每个单元格的数据 */
        for ($row = 2; $row <= $highestRow; $row++){//行数是以第2行开始
            for ($column = 'A'; $column <= "B"; $column++) {//列数是以A列开始
                $dataset[] = $sheet->getCell($column.$row)->getValue(); 
            }
        }

        /** 从url提取用户uid */
        $uids[$sheetNames[$i]] = array();
        foreach($dataset as $value){
            if(preg_match('/^http:\/\/\weibo.com\/u/i', $value)){
                $temp = explode('/', $value);
                if(isset($temp[4])){
                    $user_id = explode('?', $temp[4])[0];
                    $uids[$sheetNames[$i]][$user_id] = $value;
                    $j++;
                }
            }
        }
    }
    if($multi){
        return $uids;
    }else{
        foreach($uids as $k => $v){
            foreach($v as $key=>$val){
                $arr[$key] = $val;
            }
        }

        return $arr;
    }
}

/**  单线程查询微博API */
function curl_get($get) 
{    
    $defaults = array( 
        CURLOPT_URL => $get, 
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_RETURNTRANSFER => TRUE, 
        CURLOPT_TIMEOUT => 20
    ); 
    $ch = curl_init(); 
    curl_setopt_array($ch, $defaults); 
    if( ! $result = curl_exec($ch)) 
    { 
        @trigger_error(curl_error($ch));
    } 
    curl_close($ch); 
    return $result; 
}

/** 根据API返回数据分批获取用户及微博信息 */
function getUserData($type,$cou){
    global $allIds, $get, $count, $re_arr,$domain,$token,$re_arr;
    $domain = "c.api.weibo.com";
    $type = isset($type) ? $type : 0;
    $re_arr = getExcel(FALSE);
    $token = "2.00AgR86GMG4kED61b625e6e7JCOk3D";
    $count = $cou;

    /**
     *  对返回的userid数组进行重新组装，
     *  分别组成userid数组和url数组
     */
    foreach($re_arr as $k=>$v){
        $allIds[] = $re_userId[] = (int)$k;
        $re_userUrl[] = $v;
    }

     /**
      * 要获取的类型值，
      * 批量用户信息0，
      * 批量用户标签1，
      * 批量获取用户的粉丝数、关注数、微博数2，
      * 批量获取个人微博列表3，
      * 根据微博ID批量获取微博信息4，
      * 批量获取指定微博的转发数评论数喜欢数5
      **/

    switch($type){
        case 0:
        $get = $domain."/2/users/show_batch/other.json?access_token=".$token."&uids=";
        break;
        case 1:
        $get = $domain."/2/tags/tags_batch/other.json?access_token=".$token."&uids=";
        break;
        case 2:
        $get = $domain."/2/users/counts_batch/other.json?access_token=".$token."&uids=";
        break;
        case 3:
        $get = $domain."/2/statuses/user_timeline_batch.json?access_token=".$token."&count=20&page=1&flag=0&base_app=0&feature=0&uids=";
        break;
        case 4:
        $get = $domain."/2/statuses/show_batch/biz.json?access_token=".$token."&isGetLongText=0&trim_user=1&ids=";
        break;
        case 5:
        $get = $domain."/2/statuses/count/biz.json?access_token=".$token."&ids=";
        break;
        defualt:
        $get = $domain."/2/users/show_batch/other.json?access_token=".$token."&uids=";
        break;
    }

    /**
     * 通过userid查询0,1,2,3类型数据
     * 通过weiboid查询4,5类型数据
     * $type为类型3, 获取微博id
     */
    function getData($type = null){
        $allIds = $GLOBALS['allIds'];
        $count = $GLOBALS['count'];
        $data = [];
        $total = count($allIds);
        $query_num = ceil($total/$count);
        for($j = 0; $j < $query_num; $j++){
            $ids = implode(",",array_slice($allIds,$count * $j, $count));
            if($type == 3){
                $get = $GLOBALS['domain']."/2/statuses/user_timeline_batch.json?access_token=".$GLOBALS['token']."&count=20&page=1&flag=0&base_app=0&feature=0&uids=";
            }else{
                $get = $GLOBALS['get'];
            }
//            $task = 'task'.$j;
//            $query_task_urls[$task] = $get.$ids;
        }
        $data[] = json_decode(curl_get($get.$ids));
        $data['url']=$GLOBALS['re_arr'];
        return $data;
    }

    /**
     *  获取微博所有id
     */
    function getWeboIds(){
        $arr = getData(3);
        $size = count($arr);
        $weboIds=[];
          foreach( $arr[1]->statuses as $v){
                $weboIds[] = number_format($v->id, 0, "", "");
            }

        return $weboIds;
    }

    /**
     * 判断类型为4,5，即根据微博id查询微博数据
     */
    if($type == 4 || $type == 5){
        $allIds = getWeboIds();
    }

    return getData();

}

/**
* 启动脚本
*
* $type 要获取的类型值，
* 批量用户信息0，
* 批量用户标签1，
* 批量获取用户的粉丝数、关注数、微博数2，
* 批量获取个人微博列表3，
* 根据微博ID批量获取微博信息4，
* 批量获取指定微博的转发数评论数喜欢数5
*
* $count 每次查询限制
* 批量用户信息50，
* 批量用户标签20，
* 批量获取用户的粉丝数、关注数、微博数100，
* 批量获取个人微博列表20，
* 根据微博ID批量获取微博信息50，
* 批量获取指定微博的转发数评论数喜欢数100

*/

function run_user($type, $count){
    $config=require_once __DIR__."/common/config.php";
    $DB=DB::get_instance($config['db']);
    $data=getUserData($type, $count);
    foreach($data as $data_item)
    {
        if(!empty($data_item->users)) {
            foreach ($data_item->users as $k => $data_user) {
                if (!empty($data_user->status->text)) {
                    $text = $data_user->status->text;
                } else {
                    $text = "";
                }
                $arr = [
                    'uid' => $data_user->id,
                    "page_type" => 4,
                    "text" => $text,
                    "location" => $data_user->location,
                    "site_name" => "新浪微博",
                    "site_url" => "weibo.com",
                    "insert_time" =>strtotime($data_user->status->created_at),
                ];
                $arr_weibo = [
                    "user_name" => $data_user->name,
                    "user_id" => $data_user->id,
                    "followers_count" => $data_user->followers_count,
                    "verified" => $data_user->verified,
                    "location" => $data_user->location,
                    "statuses_count" => $data_user->statuses_count,
                    "friends_count" => $data_user->friends_count,
                    "gender" => $data_user->gender == "m" ? 1 : 2,
                    "profile_image_url" => $data_user->profile_image_url,
                    "description" => $data_user->description,
                    "create_time" => time(),
                    "update_time" => time()
                ];
                $re1 = $DB->select("select * from weibo_data where user_id='{$data_user->id}'");
                $re2 = $DB->select("select * from weibo_user where uid='{$data_user->id}'");
                if (empty($re2)) {
                    $DB->insert("weibo_user", $arr);
                } else {
                    $DB->update("weibo_user", ['uid' => $data_user->id], [
                        "text" => $text,
                        "location" => $data_user->location,
                        "insert_time" =>strtotime($data_user->status->created_at),
                    ]);
                }

                if (empty($re1)) {
                    $DB->insert("weibo_data", $arr_weibo);
                } else {
                    $DB->update("weibo_data", ["user_id" => $data_user->id], [
                        "followers_count" => $data_user->followers_count,
                        "statuses_count" => $data_user->statuses_count,
                        "friends_count" => $data_user->friends_count,
                        "profile_image_url" => $data_user->profile_image_url,
                        "description" => $data_user->description,
                        "update_time" => time()
                    ]);
                }
            }
        }
    }
}

/**
 * @param $type
 * @param $count  获取微博的id 转发数  评论数
 */

function run_weibo($type, $count)
{
    $config=require_once __DIR__."/common/config.php";
    $DB=DB::get_instance($config['db']);
    $data=getUserData($type, $count);
    foreach($data as $data_item)
    {
        if(!empty($data_item->statuses)) {
            foreach ($data_item->statuses as $k => $status) {
                $id = $status->uid;
                $text = $status->text;
                $arr = [
                    "text_content" => $text,
                    "reposts_count" => $status->reposts_count,
                    "comments_count" => $status->comments_count,
                    "attitudes_count" => $status->attitudes_count,
                    "id" => $status->mid
                ];
                $DB->update("weibo_data", ['user_id' => $id], $arr);
            }
        }
    }
}
function run_weiboId($type, $count){
    $config=require_once __DIR__."/common/config.php";
    $DB=DB::get_instance($config['db']);
    $data=getUserData($type, $count);
    foreach($data['url'] as $id=>$data_item)
    {
            $arr=[
               "url"=>$data_item,
                "url_sign"=>md5($data_item)
            ];

            $DB->update("weibo_user",['uid'=>$id],$arr);
        }

}

function run_url($type, $count)
{
    $config=require_once __DIR__."/common/config.php";
    $DB=DB::get_instance($config['db']);
    $data=getUserData($type, $count);
    foreach($data as $data_item) {
        if (!empty($data_item->statuses)) {
            foreach ($data_item->statuses as $data_user) {
                if (!empty($data_user->original_pic) || !empty($data_user->pic_ids)) {
                    $arr = [
                        "pic_ids" => json_encode($data_user->pic_ids, true),
                        "original_pic" => $data_user->original_pic
                    ];
                    $id = $data_user->user->id;
                    $DB->update("weibo_data", ['user_id' => $id], $arr);
                }
            }
        }
    }
}
/**
*  ReWeboData 外部调用，返回json串
*  $type  0返回全部, 1 返回制定条
*  $num 查询条数
*/

function ReWeboData($last_id,$num=null,$order_by=null){
    $config=require_once __DIR__."/common/config.php";
    $DB=DB::get_instance($config['db']);
    $sql="select * from weibo_user as u join weibo_data as d  on u.uid=user_id order by data_id {$order_by} limit {$last_id},$num";
    $result = $DB->select($sql);

    echo  json_encode($result);
}
//run_user(0, 1);  //获得用户的数据脚本
//run_weibo(4,1);   //获取微博id 评论数 转发数
//run_weiboId(4,1);
//print_r(getUserData(3,1));

?>